import { getUrlValue, setToken } from '@/utils/tools'
import { getSystemMenus, getUserInfo, getUserToken } from '@/api'
import { useGlobalStore } from '@/store/global'
import config from '@/config'
// import { localMenus } from './local-menus'

/**
 * 用户信息&权限校验
 */
export async function verifyAuth() {
    const globalStore = useGlobalStore()
    let isOk = true
    try {
        // 修改系统标题
        document.title = config.systemTitle
        // 暴露基座对象
        window.baseAppConfig = config
        // 通过url传递token时，获取token accessToken
        const token = getUrlValue('token')
        let href = location.href
        if (token) {
            setToken(token)
            href = href.replace(`token=${token}`, '')
        }
        if (token) {
            setTimeout(() => {
                window.history.replaceState({}, '', href)
            }, 100)
        }

        // 用户信息
        const userInfo = await getUserInfo()
        window.userInfo = userInfo
        globalStore.changeUserInfo(userInfo)

        // 自动获取token
        const resp = await getUserToken()
        if (resp && resp.data) {
            setToken(resp.data)
        }

        // 获取用户权限
        if (config.systemMenuCode) {
            const { data } = await getSystemMenus(config.systemMenuCode)
            window.systemMenusList = data.entries
        } else {
            window.systemMenusList = []
        }
        // window.systemMenusList = localMenus
    } catch (error) {
        console.error(error)
        isOk = false
    }
    return isOk
}
